<template>
  <div class="main theme-dark">
    <div class="left">
      <div class="header bg-m">
        <!-- currentType -->
        <a-tabs default-active-key="1" @change="typesClickHandler">
          <a-tab-pane :key="type.code" :tab="type.name" v-for="type in types"></a-tab-pane>
        </a-tabs>
        <div class="counts flex">
          <div class="counts-item flex1">
            <p class="title">${{ types[currentType] && types[currentType].lowPrice }}</p>
            <span class="sub-title">{{ $t('latest transaction price') }}</span>
          </div>
          <div class="counts-item flex1">
            <p class="flex1 flex alcenter jscenter title">
              <img
                alt=""
                class="wt25"
                src=""
                style="display: none"
              />
              <img
                alt=""
                class="wt25"
                src=""
              />
              <span class="ml10 green">
                {{ types[currentType] && types[currentType].priceflu }}%
              </span>
            </p>
            <span class="sub-title">{{ $t('24-hour') }}</span>
          </div>
          <div class="counts-item flex1">
            <p class="title">${{ types[currentType] && types[currentType].highPrice }}</p>
            <span class="sub-title">{{ $t('24 hours highest') }}</span>
          </div>
          <div class="counts-item flex1">
            <p class="title">${{ types[currentType] && types[currentType].openPrice }}</p>
            <span class="sub-title">{{ $t('24 hours open price') }}</span>
          </div>
          <div class="counts-item flex1">
            <p class="title">${{ types[currentType] && types[currentType].price }}</p>
            <span class="sub-title">{{ $t('24H amount') }}</span>
          </div>
        </div>
      </div>
      <div class="body bg-m">
        <div>
          <comm-chart
            ref="CommChart"
            :default-pair-name="types[currentType] && types[currentType].code"
            style="width: 100%"
          ></comm-chart>
        </div>
      </div>
      <div class="tabs flex ht50 lh50 baselight2 tc ft14 mt20" style="background-color: #0b0e11">
        <div :class="currentTab === 2 && 'active'" class="tab pointer" @click="tabsHandler(2)">
          {{ $t('in transaction') }}
        </div>
        <div :class="currentTab === 1 && 'active'" class="tab pointer" @click="tabsHandler(1)">
          {{ $t('Closed position') }}
        </div>
      </div>
      <div class="tables">
        <a-table
          :columns="
            currentTab == 2
              ? [
                  ...columns1,
                  {
                    title: $t('Countdown'),
                    scopedSlots: { customRender: 'Countdown' }
                  },
                  {
                    title: $t('Current Price'),
                    key: 'CurrentPrice',
                    dataIndex: 'CurrentPrice'
                  },
                  {
                    title: $t('Handling Fees'),
                    scopedSlots: { customRender: 'HandlingFees' }
                  },
                  {
                    title: $t('Expected profit and loss'),
                    scopedSlots: { customRender: 'Expectedprofitandloss' }
                  }
                ]
              : columns1
          "
          :data-source="data1"
          :pagination="false"
          style="color: #fff"
        >
          <template slot="Countdown" slot-scope="text, record">
            <a-statistic-countdown
              :value="new Date(record.utcTime).getTime() + 1000 * record.type"
              format="mm:ss"
              :valueStyle="{ color: '#b0b8db', fontSize: '14px' }"
            />
          </template>
          <template slot="CurrentPrice" slot-scope="text, record">
            {{ record.CurrentPrice }}
          </template>
          <template slot="HandlingFees" slot-scope="text, record">
            {{ record.buyAmount * 0.005 }}
          </template>
          <template slot="Expectedprofitandloss" slot-scope="text, record">
            {{ (record.rate / 100) * record.buyAmount - record.buyAmount * 0.005 }}
          </template>
        </a-table>
      </div>
    </div>
    <div class="right">
      <div class="header bg-m">
        <div class="flex_center title">
          <img
            alt=""
            src=""
          />
          <p>{{ $t('Delivery Account') }}</p>
        </div>
        <div class="amount">{{ amount }} USDT</div>
      </div>
      <div class="bgpart">
        <img
          alt=""
          src=""
        />
        <span class="title">{{ $t('Transaction Mode') }}</span>
      </div>
      <div class="selects">
        <div v-for="(item, i) in modes" :key="item" class="op bg-m" @click="selectModelHandler(i)">
          <div>USDT</div>
          <img
            v-if="selectModel === i"
            alt=""
            class="icon"
            src="../assets/images/contract/pitch_on.png"
          />
        </div>
      </div>
      <div class="bgpart">
        <img
          alt=""
          src=""
        />
        <span class="title">{{ $t('Transaction amounts') }}</span>
      </div>
      <div class="bgpart" style="padding: 0">
        <a-input v-model="amounts" style="height: 40px; color: #fff" type="number" />
      </div>
      <div class="bgpart">
        <img
          alt=""
          src=""
        />
        <span class="title">{{ $t('Transaction datetime') }}</span>
      </div>
      <div class="selects">
        <div
          v-for="(item, i) in productList"
          :key="item.id"
          class="op bg-m"
          @click="selectDateTimeHandler(i)"
        >
          <div>{{ item.times }}{{ $t('second') }}</div>
          <img
            v-if="selectDatetime === i"
            alt=""
            class="icon"
            src="../assets/images/contract/pitch_on.png"
          />
        </div>
      </div>

      <div class="bgpart ptb20 flex hidden-xs">
        <div class="flex flex1 alcenter jscenter">
          <img
            alt=""
            src=""
          />
          <span>{{ $t('profit rate') }}</span>
        </div>
        <div class="flex1 alcenter flex jscenter gold ft36">
          <span class="bold"> {{ productList.length ? [selectDatetime].rate : 0 }} </span>%
          <span></span>
        </div>
      </div>

      <div class="mt20 nmb_mt20 flex">
        <a-button
          :loading="submitLoading"
          class="flex1 bggreen tc ptb10 ft16 white radius40 flex alcenter jscenter pointer mb_btn mr20"
          size="large"
          @click="submitHandler('buy')"
        >
          <img
            alt=""
            src=""
          />
          <span class="white">{{ $t('Buy up') }}</span></a-button
        >
        <a-button
          :loading="submitLoading"
          class="flex1 bgred tc ptb10 ft16 white radius40 flex alcenter jscenter pointer mb_btn"
          size="large"
          @click="submitHandler('sell')"
        >
          <img
            alt=""
            src=""
          />
          <span class="white">{{ $t('Buy Down') }}</span>
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Table } from 'ant-design-vue'
import websocket from '@/utils/websocket'
import commChart from '@/components/commChart.vue'
import { fetchKStock, fetchAccount } from '@/api/asset'
import { getStockInfo, getSecondList, getSecondTrade, getSecondProductList } from '@/api/stock'

import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc' // 需引入 utc 插件

dayjs.extend(utc) // 安装插件

// assetsCoinSelect,
const columns2 = [
  {
    title: 'transaction pair',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: 'number',
    dataIndex: 'age',
    key: 'age',
    width: 100
  },
  {
    title: 'Purchase Price',
    dataIndex: 'address',
    key: 'address 1',
    ellipsis: true
  },
  {
    title: 'Transaction Price',
    dataIndex: 'address',
    key: 'address 2',
    ellipsis: true
  },
  {
    title: 'Transaction Price',
    dataIndex: 'address',
    key: 'address 3',
    ellipsis: true
  }
]
export default {
  components: {
    ATable: Table,
    commChart
  },
  data() {
    return {
      countList: [],
      columns1: [
        {
          title: this.$t('times'),
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: this.$t('orderType'),
          dataIndex: 'orderType',
          customRender: (text) => {
            if (text === 'buy') {
              return this.$t('up')
            } else if (text === 'sell') {
              return this.$t('down')
            }
            return this.$t('Unknown')
          }
        },
        {
          title: this.$t('Buy Price'),
          dataIndex: 'price',
          key: 'price'
        },
        {
          title: this.$t('Buy Amount'),
          dataIndex: 'buyAmount',
          key: 'buyAmount'
        },
        {
          title: this.$t('Closing price'),
          dataIndex: 'finalPrice',
          key: 'finalPrice'
        },
        {
          title: this.$t('Trading Products'),
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: this.$t('Profit and Loss'),
          dataIndex: 'resAmount',
          key: 'resAmount'
        }
      ],
      columns2,
      types: [],
      amount: 0,
      datetime: [30, 60, 90, 120, 150, 180],
      modes: ['USDT'],
      selectDatetime: 0,
      selectModel: 0,
      amounts: 100,
      currentTab: 2,
      currentType: 0,
      kLineData: [],
      data1: [],
      tableLoading: false,
      submitLoading: false,
      productList: [{ rate: 0 }]
    }
  },
  mounted() {
    this.loadAssetsCoinSelect()
    getSecondProductList().then((res) => {
      this.productList = res.data
    })
  },
  methods: {
    loadBalana() {
      fetchAccount({ type: 'trade', name: 'USDT' }).then((res) => {
        this.amount = res.data
      })
    },
    loadKData() {
      fetchKStock({ code: this.types[this.currentType].code, type: 1 }).then((res) => {
        // console.log('fetchKStock', res)
        this.kLineData = res.data
      })
    },
    changeType() {
      this.$refs.CommChart.ChangeSymbol(
        this.types[this.currentType].code,
        this.types[this.currentType].name
      )
    },
    loadAssetsCoinSelect() {
      getStockInfo().then((resp) => {
        resp.data.forEach((item) => {
          new websocket(function (data) {
            if (data[item.code]) {
              item.price = data[item.code].price
              item.priceflu = data[item.code].priceflu
              item.lowPrice = data[item.code].lowPrice
              item.highPrice = data[item.code].highPrice
              item.openPrice = data[item.code].openPrice
            }
          })
        })
        this.types = resp.data
        this.loadBalana()
        this.loadData()
        this.changeType()
        // this.loadKData(data[0].code)
      })
    },
    selectModelHandler(i) {
      this.selectModel = i
    },
    selectDateTimeHandler(i) {
      this.selectDatetime = i
    },
    typesClickHandler(val) {
      const index = this.types.findIndex((item) => item.code === val)
      this.currentType = index
      this.loadBalana()
      this.changeType()
    },
    loadData() {
      this.tableLoading = true
      getSecondList({ status: this.currentTab })
        .then((res) => {
          const response = res.data
          response.forEach((v) => {
            v.CurrentPrice = ''
            const localTime = dayjs.utc(v.createTime).local() // 本地时间（假设 UTC+8）
            v.utcTime = localTime.format('YYYY-MM-DD HH:mm:ss')
          })
          console.log(response, 'responseresponseresponseresponse')

          new websocket(function (data) {
            response.forEach((v) => {
              if (v.code == data.code) {
                v.CurrentPrice = data.price
              }
            })
          })
          this.data1 = response
          this.tableLoading = false
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    tabsHandler(val) {
      if (this.currentTab != val) {
        this.currentTab = val
        this.loadData()
      }
    },
    submitHandler(type) {
      const { types, currentType, productList, selectDatetime, amounts } = this
      const data = {
        type,
        id: productList[selectDatetime].id,
        name: types[currentType].name,
        amount: amounts
      }
      this.submitLoading = true
      getSecondTrade(data)
        .then(() => {
          this.submitLoading = false
          this.$Success()
          this.loadBalana()
          this.loadData()
        })
        .catch(() => {
          this.submitLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
:deep .ant-table-thead > tr > th {
  //background: rgba(255, 255, 255, 0); //去掉表头背景
  color: #fff;
  font-weight: bold;
  border: none; //去掉表头边框
}

:deep .ant-table {
  color: aliceblue;
  font-size: 12px;
  //background: rgba(255, 255, 255, 0); //去掉表格背景
}

.bg-m {
  background-color: #0b0e11 !important;
}

.gold {
  color: #ff5c0d;
}

.flex1 {
  flex: 1;
}

.flex {
  display: flex;
}

.radius40 {
  border-radius: 40px;
}

.flex_center {
  display: flex;
  align-items: center;
}

.header {
  border-radius: 5px;
  border-bottom: 1px solid #273344;
}

.green {
  color: #00ab86;
}

.main {
  padding: 24px;
  display: flex;
  flex-direction: row;
  padding-bottom: 42px;

  .right {
    width: 25%;
    display: flex;
    padding: 0 15px;
    flex-direction: column;

    .selects {
      margin-top: 15px;
      display: grid;
      grid-template-columns: repeat(3, 33.33%);

      .op {
        height: 40px;
        cursor: pointer;
        margin: 4px 0;
        border-radius: 5px;
        border: 1px solid #273344;
        width: 100px;
        padding: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        .icon {
          width: 25px;
          height: 25px;
          position: absolute;
          right: 0;
          bottom: 1px;
        }
      }
    }

    .bgpart {
      margin-top: 15px;
      padding: 10px;

      .title {
        margin-left: 13px;
        font-weight: 500;
        font-size: 14px;
        color: #f5f5f5;
      }
    }

    .header {
      //width: 90%;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;

      .title {
        font-size: 18px;
        font-weight: 600;
        margin: 20px 0;
      }

      .amount {
        margin-bottom: 24px;
        font-size: 22px;
        font-weight: 500;
      }
    }
  }

  .left {
    width: 75%;

    .tabs {
      display: flex;
      align-items: center;

      .tab {
        position: relative;
        //padding: 0;
        padding: 10px 5px;
        margin: 0 10px;
      }

      .tab.active {
        color: #fcd535;

        &::after {
          position: absolute;
          content: ' ';
          left: 0;
          bottom: 0;
          width: 100%;
          background: #fcd535;
          height: 2px;
        }
      }
    }

    .header {
      padding: 12px;
      width: 100%;

      .types {
        width: 100%;
        display: flex;
        align-items: center;

        &-item {
          //margin: 0 24px;
          padding: 12px 24px;
          font-size: 16px;
          font-weight: 500;
          min-width: 100px;
          text-align: center;
          cursor: pointer;
        }

        &-item.active {
          color: #00ab86;
          //font-weight: 900;
          position: relative;
        }

        &-item.active::after {
          position: absolute;
          bottom: 0;
          height: 2px;
          width: 100%;
          left: 0;
          content: ' ';
          background: #00ab86;
        }
      }

      .counts {
        margin-top: 15px;

        &-item {
          text-align: center;

          .title {
            color: #fff;
            font-size: 18px;
            font-weight: 500;
            margin: 8px 0;
          }

          .sub-title {
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
